package org.quipu.client;

import org.quipu.client.events.AccountsOutOfDateEvent;
import org.quipu.client.events.AppEventBus;
import org.quipu.dto.AccountDto;

public class AccountListBox extends AppListBox {

    private final String anyTitle;

    public AccountListBox(AppEventBus eventBus, AppCache cache, String anyTitle, Long selectedAccountId) {
        super(eventBus, cache, AccountsOutOfDateEvent.class, null, selectedAccountId);
        this.anyTitle = anyTitle;
        getListBox().addStyleName("accountsList");
        refresh();
    }

    @Override
    protected final void refresh() {
        getListBox().clear();
        int selectedIndex = -1;
        int i = 1;
        getListBox().addItem("", "0");
        if(anyTitle != null) {
            getListBox().addItem(anyTitle, "-1");
        }
        for(AccountDto account : getCache().getAccounts()) {
            getListBox().addItem(account.getTitle(), String.valueOf(account.getId()));
            if(account.getId().equals(getSelectedId())) {
                selectedIndex = i;
            }
            i++;
        }
        if(selectedIndex < 0) {
            setSelectedId(null);
        } else {
            getListBox().setSelectedIndex(selectedIndex);
        }
    }
}
